import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Note } from './entities/note.entity';
import { Tag } from './entities/tag.entity';
import { CreateNoteDto } from './dto/create-note.dto';
@Injectable()
export class NoteService {
  constructor(
    @InjectRepository(Note)
    private readonly noteRepository: Repository<Note>,
    @InjectRepository(Tag)
    private readonly tagRepository: Repository<Tag>,
  ) {}

  async getNoteList(): Promise<Note[]> {
    return await this.noteRepository.find();
  }
  // 获取标签列表
  async getTagList(): Promise<Tag[]> {
    return await this.tagRepository.find();
  }
  // 创建笔记
  async createNote(createNoteDto: CreateNoteDto) {
    const tags = await Promise.all(
      createNoteDto.tagName.map((name) => this.preloadTagById(name)),
    );
    console.log(tags);
    const note = this.noteRepository.create({
      ...createNoteDto,
      tags,
    });
    await this.noteRepository.save(note);
    return null;
  }
  private async preloadTagById(name: string): Promise<Tag> {
    const existingTag = await this.tagRepository.findOne({
      where: { name: name },
    });
    if (existingTag) {
      return existingTag;
    }
    return this.tagRepository.create({ name: name });
  }
}
